package cn.kgc.kgcesproduct.service;

import cn.kgc.kgcesproduct.pojo.Product;
import cn.kgc.kgcesproduct.util.Constants;
import cn.kgc.kgcesproduct.util.ELSUtil;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author geQiang
 * @version 1.0
 * @date 2019/4/14
 * @description cn.kgc.kgcesproduct.service
 */
@Service
public class ProductImpl implements ProductService {
    @Resource
    private ELSUtil elsUtil;

    @Override
    public void addIndexAndSet(String index) {
        TransportClient transportClient = elsUtil.getTransportClient();
        transportClient.admin().indices().prepareCreate(index).get();
        XContentBuilder contentBuilder = null;
        try {
            contentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("productName")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .endObject()
                    .startObject("price")
                    .field("type", "double")
                    .endObject()
                    .startObject("count")
                    .field("type", "integer")
                    .endObject()
                    .endObject()
                    .endObject();
            elsUtil.getTransportClient().admin().indices().preparePutMapping(index)
                    .setType("product")
                    .setSource(contentBuilder)
                    .get();
            transportClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addDocumetBybulk(String index) {
        TransportClient transportClient = elsUtil.getTransportClient();
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
        List<Product> p = JSONObject.parseArray(Constants.JSONDATA, Product.class);
        for (int i = 0; i < p.size(); i++) {
            Product pro = p.get(i);
            String json = JSONObject.toJSONString(pro);
            bulkRequestBuilder.add(
                    transportClient.prepareIndex(index, "product", i + "")
                            .setSource(json, XContentType.JSON));
        }
        //统一进行插入
        BulkResponse responses = bulkRequestBuilder.execute().actionGet();
        if (responses.status().getStatus() == 200) {
            System.out.println("批量插入成功---");
        } else {
            System.out.println("批量插入失败---");
        }
        transportClient.close();
    }

    @Override
    public List<Product> query(String index,String range, String name, double start, double end) {
        TransportClient transportClient = elsUtil.getTransportClient();
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(range);
        rangeQueryBuilder.gte(start);
        rangeQueryBuilder.lte(end);
        boolQueryBuilder.filter(rangeQueryBuilder);
        boolQueryBuilder.must(QueryBuilders.matchQuery("productName", name));
        searchRequestBuilder.setQuery(boolQueryBuilder);
        searchRequestBuilder.setSize(100);
        SearchResponse response = searchRequestBuilder.execute().actionGet();
        SearchHits searchHits = response.getHits();
        SearchHit[] searchHits1 = searchHits.getHits();
        System.out.println("查询到的总的数量为:" + searchHits1.length);
        List<Product> list = new ArrayList<Product>();
        for (int i = 0; i < searchHits1.length; i++) {
            System.out.println(searchHits1[i].getSourceAsString());
            JSONObject obj = JSONObject.parseObject(searchHits1[i].getSourceAsString());
            Product p = JSONObject.toJavaObject(obj, Product.class);
            list.add(p);
        }
        transportClient.close();
        return list;
    }

    /**
     * 查询所有数据
     */
    public void queryAll() {
        TransportClient transportClient = elsUtil.getTransportClient();
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("pro_01");
        searchRequestBuilder.setSize(100);
        SearchResponse response = searchRequestBuilder.execute().actionGet();
        SearchHits searchHits = response.getHits();
        SearchHit[] searchHits1 = searchHits.getHits();
        System.out.println("查询到的总的数量为:" + searchHits1.length);
        for (int i = 0; i < searchHits1.length; i++) {
            System.out.println(searchHits1[i].getSourceAsString());
        }
        transportClient.close();
    }

}
